package net.martinimix.bizact.validation;

import java.util.List;

import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;

import com.bluemartini.dna.BMException;
import com.bluemartini.dna.DNAList;
import com.bluemartini.html.HTMLContext;
import com.bluemartini.html.HTMLResponse;
import com.bluemartini.server.BusinessAction;

/**
 * Provides an abstract Blue Martini form validator.
 * 
 * @author Scott Rossillo <scottr@jr.com>
 *
 */
public abstract class AbstractBlueMartiniFormValidator extends BusinessAction implements BlueMartiniFormValidator {

	/**
	 * Creates a new abstract form validator.
	 */
	protected AbstractBlueMartiniFormValidator() {
		super();
	}
	
	/* (non-Javadoc)
	 * @see com.bluemartini.server.BusinessAction#execute(com.bluemartini.dna.DNAList)
	 */
	public final DNAList execute(DNAList dnaIn) throws BMException {
		
		final Errors errors = new BlueMartiniFormErrors(dnaIn);
		final HTMLResponse response = new HTMLResponse();
		
		try {
			this.validate(dnaIn.getList(HTMLContext.REQUEST_FORM_DATA), errors);
		} catch (Exception ex) {
			throw new BMException("Validation failed with error: " + ex.getMessage(), ex, null);
		}
		
		response.setObject("errors", errors);
		
		if(errors.hasGlobalErrors()) {
			response.setFormValid(false);
		}
		
		final List fieldErrors = errors.getFieldErrors();
		
		for(int i = 0 ; i < fieldErrors.size(); i++) {
			
			final FieldError fieldError = (FieldError) fieldErrors.get(i);
			final String field = fieldError.getField();
			
			response.setValid(field, false);
			response.setError(field, fieldError.getCode());	
		}
		
		return response;
	}
}
